import math

from django.core.paginator import Paginator
from django.db.models import Max, Min, Count, Sum, Avg
from django.http import HttpResponse
from django.shortcuts import render
from app.models import PersonModel


# Create your views here.
def add_person(request):
    # 方式一
    # try:
    #     p = PersonModel()
    #     p.name = "zhangsan"
    #     p.age = 44
    #     p.save()
    # except Exception as e:
    #     return HttpResponse('重名，添加失败')
    # return HttpResponse('添加成功')

    # 方式二
    # try:
    #     p = PersonModel(name="lisi", age=36)
    #     p.save()
    # except Exception as e:
    #     return HttpResponse('重名，添加失败')
    # return HttpResponse('添加成功')

    # 方式三
    # try:
    #     PersonModel.objects.create(name="wangwu", age=36)
    # except Exception as e:
    #     return HttpResponse('重名，添加失败')
    # return HttpResponse('添加成功')

    # 方式四
    for i in range(20):
        try:
            r = PersonModel.objects.get_or_create(name=f"zhaoliu{i}", age=i+20)
        except Exception as e:
            return HttpResponse('重名，添加失败')
    return HttpResponse(r)


def del_person(request):
    # 删除1条
    # try:
    #     p = PersonModel.objects.first()
    #     p.delete()
    # except Exception as e:
    #     return HttpResponse('删除失败')
    # return HttpResponse('删除成功')

    # 删除多条
    try:
        p = PersonModel.objects.filter(age__gt=15).delete()
    except Exception as e:
        return HttpResponse('删除失败')
    return HttpResponse('删除成功')


def update_person(request):
    # 修改1条
    # try:
    #     p = PersonModel.objects.first()
    #     p.age = 70
    #     p.save()
    # except Exception as e:
    #     return HttpResponse('修改失败')
    # return HttpResponse('修改成功')

    # 修改多条
    # try:
    #     p = PersonModel.objects.all().update(age=100)
    # except Exception as e:
    #     return HttpResponse('修改失败')
    # return HttpResponse('修改成功')

    # 指定更新字段（save默认更新所有字段，可以指定字段，减少开销）
    p = PersonModel.objects.first()
    p.age = 70
    p.save(update_fields=['age'])


def get_person(request):
    # p = PersonModel.objects.get(id=1)  # 得到1个对象，找不到或找到多个均报错
    # p = PersonModel.objects.all()  # 返回查询集QuerySet，可循环获取对象
    # p = PersonModel.objects.first()  # 返回第1条数据
    # p = PersonModel.objects.last()  # 返回最后1条数据
    # p = PersonModel.objects.filter()  # 过滤数据 in
    # p = PersonModel.objects.exclude()  # not in
    # p = PersonModel.objects.filter().exists()  # 查询集是否有数据
    # p = PersonModel.objects.filter().count()  # 查询集总数
    #
    # p = PersonModel.objects.filter().values()  # 返回列表套字典
    # p = PersonModel.objects.filter().values('name')  # 返回列表套字典
    # p = PersonModel.objects.filter().values_list('name')  # 返回列表套元组

    # 聚合函数
    p = PersonModel.objects.aggregate(Max('age'))  # 最大值
    print(p.get('age__max'))
    p = PersonModel.objects.aggregate(Min('age'))
    p = PersonModel.objects.aggregate(Sum('age'))
    p = PersonModel.objects.aggregate(Avg('age'))
    p = PersonModel.objects.aggregate(Count('age'))

    # 排序
    p = PersonModel.objects.all().order_by('age')  # 升序
    p = PersonModel.objects.all().order_by('age', 'id')  # 先age升序，再id升序
    p = PersonModel.objects.all().order_by('-age')  # 降序
    return HttpResponse('查询成功')


# 手动分页
def pages(request, page=1):
    per_page = 10
    persons = PersonModel.objects.all()
    persons = persons[(page-1)*per_page:page*per_page]

    total = PersonModel.objects.count()
    total_pages = math.ceil(total / per_page)
    total_pages = range(1, total_pages+1)

    return render(request, 'pages.html', {'persons': persons, 'total': total_pages})


# 分页器
def pages2(request, page=1):
    per_page = 10
    datas = PersonModel.objects.all()
    paginator = Paginator(datas, per_page)
    persons = paginator.page(page)
    total = paginator.page_range
    return render(request, 'pages2.html', {'persons': persons, 'total': total})
